const auth = require('../../api/auth');

Page({
  onLogin() {
    wx.getUserProfile({
      desc: '用于完善会员资料',
      success: userRes => {
        const { nickName, avatarUrl } = userRes.userInfo;
        wx.login({
          success: res => {
            if (res.code) {
              auth.wxLogin(res.code, nickName, avatarUrl).then(data => {
                console.log('data', data);
                wx.setStorageSync('token', data.data.token);
                getApp().globalData.token = data.data.token;
                wx.setStorageSync('userInfo', data.data.userInfo);
                getApp().globalData.userInfo = data.data.userInfo;
                // 判断资料和成员绑定
                if (!data.data.isProfileComplete) {
                  wx.redirectTo({ url: '/pages/profile/complete/index' });
                } else {
                  wx.showToast({ title: '登录成功', icon: 'success' });
                  wx.switchTab({ url: '/pages/index/index' });
                }
              }).catch(() => {
                wx.showToast({ title: '登录失败', icon: 'none' });
              });
            } else {
              wx.showToast({ title: '获取code失败', icon: 'none' });
            }
          },
          fail: () => {
            wx.showToast({ title: '微信登录失败', icon: 'none' });
          }
        });
      },
      fail: () => {
        wx.showToast({ title: '需要授权获取用户信息', icon: 'none' });
      }
    });
  }
});
